/**
 * 
 */
package cn.dlike.LunarCalendar.util;

import java.io.File;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;

/**
 * 发送邮件Util
 * 
 * @author Qjzhyf
 *
 */
public class EmailUtil {

	private static String EMAIL_HOST_NAME = "smtp.qq.com";
	private static int SMTP_PORT = 465;
	private static String DEFAULT_SENDER = "991357524@qq.com";
	private static String DEFAULT_SENDER_NAME = "dlike";
	private static String DEFAULT_SENDER_PASSWORD = "dfhwwunkjngmbcej";
	private static boolean NEED_SSL = true;
	
	public static void config(String hostName, int hostPort, boolean needSSL, String senderAddress, String senderName, String senderPassword) {
		EMAIL_HOST_NAME = hostName;
		SMTP_PORT = hostPort;
		NEED_SSL = needSSL;
		DEFAULT_SENDER = senderAddress;
		DEFAULT_SENDER_NAME = senderName;
		DEFAULT_SENDER_PASSWORD = senderPassword;
	}

	/**
	 * sendEmail
	 * 
	 * @param toEmail
	 *            客户email
	 * @param toEmailName
	 *            客户姓名
	 * @param subject
	 *            邮件主题
	 * @param bodyHtml
	 *            邮件正文
	 * @param attachFile
	 *            附件路径
	 * @param attachName
	 *            附件文件名称
	 * @return boolean
	 */
	public static boolean sendEmail(String toEmail, String toEmailName, String subject, String bodyHtml,
			String attachFile, String attachName) {
		boolean isOk = false;
		HtmlEmail email = new HtmlEmail();
		email.setHostName(EMAIL_HOST_NAME);
		email.setSmtpPort(SMTP_PORT);
		email.setSSLOnConnect(NEED_SSL);
		email.setCharset("UTF-8");
		try {
			email.setAuthenticator(new DefaultAuthenticator(DEFAULT_SENDER, DEFAULT_SENDER_PASSWORD));
			email.addTo(toEmail, toEmailName);
			email.setFrom(DEFAULT_SENDER, DEFAULT_SENDER_NAME);
			email.setSubject(subject);
			email.setHtmlMsg(bodyHtml);

			if (attachFile != null && attachFile != "" && attachName != null && attachName != "") {
				// add the attachment
				EmailAttachment attachment = new EmailAttachment();
				attachment.setPath(attachFile);
				attachment.setDisposition(EmailAttachment.ATTACHMENT);

				String fileName = attachFile.substring(attachFile.lastIndexOf(File.separator) + 1); // XXXX.docx
				String[] fileArrays = fileName.split("\\."); // [XXXX, docx]
				attachment.setDescription(attachName); // 
				attachment.setName(attachName + "." + fileArrays[1]);
				email.attach(attachment);
			}
			// send the email
			email.send();
			isOk = true;
		} catch (EmailException e) {
			e.printStackTrace();
		}
		return isOk;
	}

}
